const Koa = require('koa')
const logger = require('koa-logger')
const convert = require('koa-convert');
const path = require('path')
const cors = require('koa2-cors')
const {koaBody} = require('koa-body')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const bodyparser = require('koa-bodyparser')

const serve = require('koa-static-server')

const config = require('config')
const { koaSwagger } = require('koa2-swagger-ui');
const routing = require('./router')
const swagger = require('./swagger')





const app = new Koa()
//app.use(catchError)

const { host,port } = config.get('Customer.initConfig');
app.use(koaSwagger({
  routePrefix: '/swagger_UZi0GMNf0tw037FSYgMn15Fri8WKm7lG', // host at /swagger instead of default /docs
  swaggerOptions: {
    url: '/swagger.json', // example path to json 其实就是之后swagger-jsdoc生成的文档地址
  },
}))

app.use(swagger.routes(), swagger.allowedMethods());

app.use(error({
  postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
}));
//解决跨域
app.use(cors())


app.use(logger())
// 加载路由中间件

app.use(async (ctx, next) => {
  let readIp = ctx.get("X-Real-IP") || ctx.get("X-Forwarded-For")  || ctx.ip;
  if ((ctx.originalUrl).indexOf('/api/v1') === 0 && ctx.state._user_id) {
    console.log(`ip: ${readIp} user_id: ${ctx.state._user_id} nickname: ${ctx.state._user.nickname}`)
  } else if ((ctx.originalUrl).indexOf('/admin/') === 0 && ctx.state._user_id) {
    console.log(`ip: ${readIp} user_id: ${ctx.state._user_id} username: ${ctx.state._user.username}`)
  } else if ((ctx.originalUrl).indexOf('/common/') === 0) {
    console.log(`ip: ${readIp}`)
  }else {
    console.log(`异常IP情况: ${readIp}`)
    // return false;
  }
  await next()

})

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, '/public/uploads'),
    keepExtensions: true,
  }
}))

app.use(parameter(app))

routing(app)

module.exports = app
